
import csv
import time
import threading
from simplehtf.core.test import Test
from simplehtf.utils import func,file

class NativeLauncher:
    def __init__(self):
        self.test = None
        self._test_finish_callback = None
        self._test_thread = None

    def _test_thread_func(self,):
        self.test.execute()
        if self._test_finish_callback != None:
            self._test_finish_callback(self.test.test_record)

    def _poll_for_start_thread(self,callback):
        while not callback():
            time.sleep(0.1)
        self._test_thread = threading.Thread(daemon=True,target=self._test_thread_func,)
        self._test_thread.start()

    def _poll_for_start(self,callback):
        t = threading.Thread(daemon=True,target=self._poll_for_start_thread,args=(callback,))
        t.start()
        

    def load_test_from_instance(self,test:Test):
        self.test = test
        self.test.build_phases()

    def load_test_from_csv(self,file_path,formatter = None):
    #其实我更推荐json加载器
        func_nodes = []
        with open(file_path,mode='r') as f:
            reader = csv.DictReader(f) #以字典方式加载csv文件
            for row in reader:
                if formatter == None:
                    _func = NativeLauncher.default_csv_formatter(row)
                else:
                    _func = formatter(row)
                func_nodes.append(_func)
        self.test = Test(*func_nodes,name = file.get_filename_no_ext(file_path))
        self.test.build_phases()

    def load_test_from_json(self,file_path):
        #TODO 实现json test加载器
        # with open(file_path,mode='r') as f:
        #     import json
        #     test_dict = json.load(f)
        #     print(test_dict)

        self.test.build_phases()

    def test_finish_callback(self,callback):
        self._test_finish_callback = callback

    def wait_for_finsh(self):
        self._test_thread.join()

    @staticmethod
    def default_csv_formatter(row):
        _func = func.func_generator(
                row['matcher'],
                args = row['args'],
                expected_value = row['expected_value'],
                mode = row['mode'])
        _func.__name__ = row['test_item']
        return _func
    
    def run(self):
        pass

class NativeUILauncher(NativeLauncher):
    def __init__(self):
        super().__init__()
    
    def _poll_for_start(self):
        pass
    
    def run(self):
        pass